<template>
  <el-row :gutter="0">
  <el-col :xs="2" :sm="3" :md="4" :lg="4" :xl="4">
    <div class="hidBoth">郭于</div>
  </el-col>

  <el-col :xs="20" :sm="18" :md="16" :lg="16" :xl="16">
  <div class="containDetail">
  <el-row :gutter="0">
        
  <el-col :xs="1" :sm="1" :md="1" :lg="3" :xl="6">
      <div class="hidBoth">郭于</div>
  </el-col>
  <el-col :xs="22" :sm="22" :md="22" :lg="18" :xl="12">
  <el-carousel :interval="400000" type="card" height="130px" indicator-position="outside">
    <el-carousel-item v-for="(img,id) in listData" :key="id">

    <div class="Img"><img :src="img.imgData" ></div>  

    <div class="dtl">{{img.name}}</div>

    </el-carousel-item>
  </el-carousel>
  </el-col>
  <el-col :xs="1" :sm="1" :md="1" :lg="3" :xl="6">
      <div class="hidBoth">郭于</div>
  </el-col>
  </el-row>
  <el-input class="iptSearch" v-model="productSearch" placeholder="输入关键字搜索"/> 
  <!-- 商品列表  -->
  <el-table  
    style="width: 100%" row-key="id" :expand-row-keys="expands"
    @row-click="rowClick" border :default-sort = "{prop: 'number', order: 'descending'}"
    :data="listData.filter(data => !productSearch || data.name.toLowerCase().includes(productSearch.toLowerCase()))"
    >
    <el-table-column type="expand">
      <template slot-scope="props">
        <el-form label-position="left" inline class="demo-table-expand">
        <div class="buttonTop">
          <el-button
            type="primary"
            @click="changeDialogOpen()"
            round
          >
            修改商品属性
          </el-button>
          </div>
          <el-form-item label="商品名称" style="width: 50%">
            <span>{{ props.row.name }}</span>
          </el-form-item>
          <el-form-item label="创建时间" style="width: 50%">
            <span>{{ props.row.ctime | dataFormat }}</span>
          </el-form-item>
          <el-form-item label="商品数量" style="width: 50%">
            <span>{{ props.row.number }}</span>
          </el-form-item>
          <el-form-item label="商品单价" style="width: 50%">
            <span>{{ props.row.price }} 元</span>
          </el-form-item>
          <el-form-item label="商品总价" style="width: 50%">
            <span>{{ props.row.price }} 元</span>
          </el-form-item>
          <el-form-item label="图片" style="width: 50%">
            <span><img :src="props.row.imgData" ></span>          
          </el-form-item>
          <el-form-item label="商品描述" style="width: 100%">
            <span>{{ props.row.detail }}</span>
          </el-form-item>
        </el-form>
      </template>
    </el-table-column>
    <el-table-column
      label="商品名"
      prop="name"
      min-width='50%'
      align="left"
      >
    </el-table-column>
    <el-table-column
      sortable
      label="商品数量"
      prop="number"
      min-width='35%'
      align="center">
    </el-table-column>
    <el-table-column  label="删除" min-width='15%'  align="center">
      <template slot-scope="scope">
        <el-button
          type="danger"
          icon="el-icon-delete"
          circle
          @click.prevent="remove(scope.$index)"
        >
        </el-button>
    </template>
    </el-table-column>
  </el-table>
    <!-- 提示框 -->
    <el-dialog
      title="提示"
      :visible.sync="changeDialogVisible"
      width="70%"
      @close="changeDialogClose"
    >
      <!-- Start 添加表单 -->
      <!-- model 是当前表单要绑定的数据对象 -->
      <el-form
        ref="changeFormRef"
        :model="changeForm"
        :rules="changeFormRules"
        label-width="6rem" 
      >
        <!-- 在el-form-item 中，label 用来指定label标签的内容 -->
        <!-- 在el-form-item prop 用来指定当前项目使用哪个验证规则 规则从 changeFormRules 上取得-->
        <el-form-item label="品牌名称" prop="productName">
          <el-input v-model="changeForm.productName"></el-input>
        </el-form-item>

        <el-form-item label="数量" prop="productNum">
          <el-input-number v-model="changeForm.productNum" :min="1"></el-input-number>
        </el-form-item>       

        <el-form-item label="单价" prop="productPrc">
          <el-input-number v-model="changeForm.productPrc" :min="1"></el-input-number>
          总价: {{changeForm.productNum}}  * {{changeForm.productPrc}} = {{changeForm.productNum*changeForm.productPrc}} 元
        </el-form-item>   
        <el-form-item label="商品细节" prop="productDtl">
          <el-input   type="textarea" :rows="5" placeholder="请输入内容（可忽略）" v-model="changeForm.productDtl"></el-input>
        </el-form-item>

      <el-form-item label="商品图片" prop="productImg">
        <div style="color: #99a9bf">原图片：</div>
          <img width="146px" :src="dialogImageUrl" alt="">
        <div style="color: #99a9bf">修改图片：（如果不改可以不选）</div>

        <el-upload
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="getImgNme"
          :on-exceed="handleExceed"
          :limit="1"
          ref="imgRef"
          >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="changeDialogClose">重置</el-button>
        <el-button type="primary" @click="changeNewProduct">确 定</el-button>
      </span>
    </el-dialog>
  </div>
  </el-col>

  <el-col :xs="2" :sm="3" :md="4" :lg="4" :xl="4">
    <div class="hidBoth">郭于</div>
  </el-col>
  </el-row >   
</template>

<script>
export default {
  data() {
    return {
        listData:[],
        productSearch:'',
        changeDialogVisible: false,
        // 添加表单所绑定的数据对象
        changeForm: {
          id:"",
          productName: "",
          productNum: "",
          productPrc: "",
          productDtl:'',
          productImg:'',
        },
          // 添加表单的验证规则对象
          changeFormRules: {
          // 验证：品牌名称是否合法的 规则
          productName: [
            { required: true, message: "请输入商品名称", trigger: "blur" },
          ],        
          productNum: [
            { required: true, message: "请输入商品数量", trigger: "blur" },
          ],
        },
        dialogImageUrl : '',
        dialogVisible : false,
        expands: [],
        openRow:''
    }
  },
  created() {
    this.getProductList();

  },
  methods: {
    getProductList() {
      
      this.listData = JSON.parse(localStorage.getItem("productList"));

      for(let i=0;i<this.listData.length;i++){
        if(this.listData[i].imgData.indexOf("../images/","") != -1){
      this.listData[i].imgData=this.listData[i].imgData.replace("../images/","");
      this.listData[i].imgData=require('../images/'+this.listData[i].imgData);          
        }

      }
  
      if (this.listData !== null) {
        return this.listData;
      } else {
        return [];
      }
    },
    // 点击行打开展开行
    //在<table>里，我们已经设置row的key值设置为每行数据id：row-key="name"
    rowClick(row) {
        Array.prototype.remove = function (val) {
            let index = this.indexOf(val);
            if (index > -1) {
                this.splice(index, 1);
            }
        };
            this.openRow=row
        if (this.expands.indexOf(row.id) < 0) {
            this.expands.push(row.id);
        } else {
            this.expands.remove(row.id);
        }

    },
    changeDialogOpen(){
      this.changeDialogVisible = true
      this.changeForm.id = this.openRow.id;
      this.changeForm.productName = this.openRow.name;
      this.changeForm.productNum = this.openRow.number;
      this.changeForm.productPrc = this.openRow.price;
      this.changeForm.productDtl = this.openRow.detail;
      this.changeForm.productImg = this.openRow.imgData;
      this.dialogImageUrl = this.openRow.imgData;
    }, 
    changeDialogClose() {
      this.$refs.changeFormRef.resetFields();
      this.$refs.imgRef.clearFiles();
      Object.keys(this.changeForm).forEach(key => (this.changeForm[key] = ''));

      this.dialogImageUrl = '';    
      },

    // 点击按钮，添加新品牌
    changeNewProduct() {
      const local = this.getProductList();
   
      if(this.changeForm.productName == '')
      return this.$message.error("修改商品失败！");

      if(this.changeForm.productNum < 1)
      return this.$message.error("修改商品失败！");

      if(this.changeForm.productPrc ==='')
      {
        this.changeForm.productPrc=1
      }
      
      if(this.changeForm.productImg ==='')
      {
        this.changeForm.productImg='../images/错误.jpg'
      }

      this.changeForm.ctime = new Date();

      this.$set(local[(this.changeForm.id-1)], `name`, this.changeForm.productName)
      this.$set(local[(this.changeForm.id-1)], `ctime`, this.changeForm.ctime)
      this.$set(local[(this.changeForm.id-1)], `number`, this.changeForm.productNum)
      this.$set(local[(this.changeForm.id-1)], `price`, this.changeForm.productPrc)
      this.$set(local[(this.changeForm.id-1)], `detail`, this.changeForm.productDtl)
      this.$set(local[(this.changeForm.id-1)], `imgData`, this.changeForm.productImg)

      localStorage.setItem("productList", JSON.stringify(local));

      this.$message.success("添加商品成功！");
      // 隐藏对话框
      this.changeDialogVisible = false;
      // 刷新列表
      this.getProductList();
    },
    getImgNme(file) {
    const isJPG = file.raw.type === 'image/jpeg';
    const isPNG = file.raw.type === 'image/png';
    const isLt200k = file.size / 1024  < 200;
    if ((!isJPG)&&(!isPNG)) {
      this.$message.error('上传图片只能是 JPG或PNG 格式!');
      file.url=''
      return
    }    
    if (!isLt200k) {
      this.$message.error('上传图片大小不能超过 200k!');
      file.url=''
      return
    }
    this.changeForm.productImg='../images/'+file.name;
    return isJPG && isPNG && isLt200k;    
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    async remove(id) {
      let removeData = localStorage.getItem("productList");

      removeData = JSON.parse(removeData);

      await this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeData.splice(id, 1);
          localStorage.setItem("productList", JSON.stringify(removeData));
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      this.getProductList();
    },    
  }    
};
</script>

<style lang="less" >
.containDetail {
    margin-top: 1.3rem;
  .iptSearch {
    margin-bottom: 1.3rem;
  }
  .el-carousel__item--card.is-in-stage {
    text-align: center;
  }
  .Img {
    width: 100%;
    height: 110px;
   img {
    display: block;
    margin: 0 auto;
    height: 100%;
    }
    .dtl {
    height: 16px;
    line-height: 16px;
  }
  }
  .el-table__row {
    cursor: pointer;
  }
  .demo-table-expand {
    font-size: 0;
  }
  label {
    width: 90px;
    color: #99a9bf;
  }
}

</style>